package com.pumpkin.web.busi.controller;

import com.pumpkin.web.busi.dao.UserDao;
import com.pumpkin.web.model.Gender;
import com.pumpkin.web.model.UserModel;
import com.pumpkin.web.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

/**
 * (description)
 *
 * @author jinlong.liao on 2016/6/30
 */
@Controller
@RequestMapping("/user")
public class UserController extends BaseController {

    @Autowired
    UserDao userDao;

    @RequestMapping(method = RequestMethod.GET)
    public String userListPage(ModelMap modelMap) {
        modelMap.addAttribute("userList", userDao.queryList());
        return "user/center";
    }

    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public String addUserPage(ModelMap modelMap) {
        modelMap.addAttribute("user", new UserModel());
        return "user/add";
    }

    @RequestMapping(value = "/update", method = RequestMethod.GET)
    public String updateUser(@RequestParam Integer id, ModelMap modelMap) {
        modelMap.addAttribute("user", userDao.queryById(id));
        modelMap.addAttribute("genders", Gender.values());
        return "user/update";
    }

    @RequestMapping(value = "/addOrUpdate", method = RequestMethod.POST)
    // TODO : bindingResult 没有成功把错误信息输出到页面
    public String addOrUpdateUser(UserModel userModel, BindingResult bindingResult) {
        int id = userModel.getId();

        if (bindingResult.hasErrors()) {
            if (id == 0) {
                return "redirect:/user/add";
            } else {
                return "redirect:/user/update?id=" + id;
            }
        }

        if (id == 0) {
            userDao.add(userModel);
        } else {
            userDao.update(userModel);
        }

        return "redirect:/user";
    }

    @RequestMapping(value = "/delete/{id}", method = RequestMethod.POST)
    @ResponseBody
    public Result deleteUser(@PathVariable Integer id) {
        userDao.delete(id);
        return Result.success();
    }
}
